/**
 * Created by yfyuan on 2016/10/28.
 */
'use strict';
cBoard.service('chartService', function ($q, dataService, chartPieService, chartLineService,$timeout, chartFunnelService,$http,
                                         chartSankeyService, chartTableService, chartKpiService,chartGaugeService, chartRadarService, chartMapService, chartScatterService) {
        var self = this;
        this.render = function (containerDom, widget, optionFilter, scope, reload, persist) {
            self.widget = widget;
            if(widget.config){
                var theme = widget.config.theme;
            }else{
                var theme = "shine";
            }

            var deferred = $q.defer();
            var chart = getChartServices(widget.config);
            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget, function (data) {
                try {
                    var option = chart.parseOption(data);
                    if (optionFilter) {
                        optionFilter(option);
                    }
                    if (data.drill) {
                        data.drill.drillDown = function (id, value, render) {
                            dataService.getDrillPath(widget.datasetId, id).then(function (path) {
                                var i = 0;
                                _.each(path, function (e, _i) {
                                    if (e.id == id) {
                                        i = _i;
                                    }
                                });
                                var node = path[++i];
                                _.find(widget.config.keys, function (e, _i) {
                                    if (e.id == id) {
                                        e.type = '=';
                                        e.values = [value];
                                        if (!_.find(widget.config.keys, function (e) {
                                                return e.id == node.id;
                                            })) {
                                            widget.config.keys.splice(_i + 1, 0, node);
                                        }
                                        return true;
                                    }
                                });
                                _.find(widget.config.groups, function (e, _i) {
                                    if (e.id == id) {
                                        e.type = '=';
                                        e.values = [value];
                                        if (!_.find(widget.config.groups, function (e) {
                                                return e.id == node.id;
                                            })) {
                                            widget.config.groups.splice(_i + 1, 0, node);
                                        }
                                        return true;
                                    }
                                });
                                dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                                    var option = chart.parseOption(data);
                                    if (optionFilter) {
                                        optionFilter(option);
                                    }
                                    render(option, data.drill.config);
                                });
                            });
                        };
                        data.drill.drillUp = function (id, render) {
                            _.find(widget.config.keys, function (e, _i) {
                                if (e.id == id) {
                                    widget.config.keys[_i - 1].values = [];
                                    widget.config.keys.splice(_i, 1);
                                    return true;
                                }
                            });
                            _.find(widget.config.groups, function (e, _i) {
                                if (e.id == id) {
                                    widget.config.groups[_i - 1].values = [];
                                    widget.config.groups.splice(_i, 1);
                                    return true;
                                }
                            });
                            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                                var option = chart.parseOption(data);
                                if (optionFilter) {
                                    optionFilter(option);
                                }
                                render(option, data.drill.config);
                            });
                        };
                    }
                } finally {

                    var chartObj  = chart.render(containerDom, option, scope, persist, data.drill,function(param){

                        if(widget.linkageInfo){

                            if(widget.linkageInfo.object){
                                var container= widget.linkageInfo.object;
                                var  linkJsonConfig ={};
                                linkJsonConfig.activeWidgetConfig=[{"widgetId":widget.linkageInfo.linkageWidgetId,"col":param.name}];
                                var bylinkages = widget.linkageInfo.bylinkage;
                                var bylinkageId = widget.linkageInfo.bylinkageId;
                                var arr =[];
                                angular.forEach(bylinkages,function(data){
                                    arr.push({"widgetId":bylinkageId,"col":data.col});
                                })
                                linkJsonConfig.passiveWidgetConfig=arr;
                                var bylinkageWidget =widget.linkageInfo.bylinkage.data;
                              //  angular.forEach(bylinkages,function(data){
                                    //arr.push({"widgetId":data.widgetId,"col":config.col});
                                    var chartData = {
                                        linkJsonConfig :linkJsonConfig,
                                        config: bylinkageWidget.config,
                                        datasource:  null,
                                        query: bylinkageWidget.query,
                                        datasetId: bylinkageWidget.datasetId
                                    }
                                    self.render(container, chartData, optionFilter, scope, true).then(function (d) {
                                      ///  bylinkageWidget.realTimeTicket = d;
                                        //       widgetObj.loading = false;
                                    });
                              //  })


                            }else{

                                var linkageWidgetId = widget.linkageInfo.linkageWidgetId;
                                var bylinkageInfos = widget.linkageInfo.bylinkage;


                                angular.forEach(bylinkageInfos,function(bylinkageInfo){
                                    angular.forEach(bylinkageInfo.bylinkageWidget,function(widgetObj){

                                       // widgetObj = bylinkageInfo.bylinkageWidget;
                                        var container = widgetObj.container;
                                        var linkJsonConfig={};
                                        // widgetObj.show = false;
                                        linkJsonConfig.activeWidgetConfig=[{"widgetId":linkageWidgetId,"col":param.name}];
                                        var arr = [];
                                        angular.forEach(bylinkageInfo.passiveWidgetConfig,function(config){
                                            arr.push({"widgetId":config.widgetId,"col":config.col});
                                        })

                                        linkJsonConfig.passiveWidgetConfig=arr;
                                        var chartData = {
                                            linkJsonConfig :linkJsonConfig,
                                            config: widgetObj.widget.data.config,
                                            datasource:  null,
                                            query: widgetObj.widget.data.query,
                                            datasetId: widgetObj.widget.data.datasetId
                                        }
                                        widgetObj.linkJsonConfig = linkJsonConfig;
                                        //widget.render(widget.container);
                                        widgetObj.render = function (content, optionFilter, scope) {
                                            self.render(content, chartData, optionFilter, scope, true).then(function (d) {
                                                widgetObj.realTimeTicket = d;
                                                //       widgetObj.loading = false;
                                            });
                                            widgetObj.realTimeOption = {optionFilter: optionFilter, scope: scope};
                                        };
                                        $timeout(function () {
                                            //  widgetObj.loading = true;
                                            //  widgetObj.show = true;
                                            widgetObj.render(container);
                                        });

                                    })

                                });
                            }

                        }
                    },theme);

                    deferred.resolve(chartObj);
                }
            }, reload);

            return deferred.promise;
        };

        this.realTimeRender = function (realTimeTicket, widget, optionFilter, scope) {
            if (!realTimeTicket) {
                return;
            }
            var chart = getChartServices(widget.config);
            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget, function (data) {
                var option = chart.parseOption(data);
                if (optionFilter) {
                    optionFilter(option);
                }
                realTimeTicket(option, data.drill.config);
            });
        };
        var changeChart = function(param){



        }
    var getWidgetById =function(widgetId){
        var widgetList;
        $http.get("dashboard/getWidgetList.do").success(function (response) {
           widgetList = response;
            return  _.find(widgetList, function (w) {
                return w.id == widgetId;
            })
        });

    }
        var getChartServices = function (chartConfig) {
            var chart;
            switch (chartConfig.chart_type) {
                case 'line':
                    chart = chartLineService;
                    break;
                case 'pie':
                    chart = chartPieService;
                    break;
                case 'kpi':
                    chart = chartKpiService;
                    break;
                case 'table':
                    chart = chartTableService;
                    break;
                case 'funnel':
                    chart = chartFunnelService;
                    break;
                case 'sankey':
                    chart = chartSankeyService;
                    break;
                case 'radar':
                    chart = chartRadarService;
                    break;
                case 'map':
                    chart = chartMapService;
                    break;
                case 'scatter':
                    chart = chartScatterService;
                    break;
                case 'gauge':
                    chart = chartGaugeService;
                    break;
            }
            return chart;
        };


    }
);